#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/11/12 11:21
# @Author  : cfg
# @File    : info_ui.py
# @Software: PyCharm
import subprocess
import threading
import tkinter
from tkinter import Toplevel, font, END
from tkinter.scrolledtext import ScrolledText


class InfoUI(threading.Thread):
    def __init__(self, cmd, w, h, x, y):
        super().__init__()
        self.cmd = cmd
        self.top_level = Toplevel()
        self.top_level.title("安装信息")
        self.top_level.geometry("%dx%d+%d+%d" % (w, h, x, y))

        self.font_YaHei_10 = font.Font(family="Microsoft YaHei", size=10)
        self.font_YaHei_12 = font.Font(family="Microsoft YaHei", size=12)
        self.text = ScrolledText(self.top_level, width=20, height=20)
        self.text.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.text.place(x=20, y=20, width=580, height=420)
        self.text.config(font=self.font_YaHei_10)

        self.btn_cancel = tkinter.Button(self.top_level, text=" 关  闭 ", background='IndianRed', command=self.on_btn_cancel_click)
        self.btn_cancel.place(x=270, y=450, width=60, height=30)
        self.btn_cancel.config(font=self.font_YaHei_10)
        self.btn_cancel.bind('<Enter>', self.on_btn_cancel_hover)
        self.btn_cancel.bind('<Leave>', self.on_btn_cancel_no_hover)

    def run(self):
        try:
            process = subprocess.Popen(self.cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

            while process.poll() is None:
                out = process.stdout
                if out:
                    stdout_line = out.readline()
                    if stdout_line:
                        line = stdout_line.decode("gbk")
                        self.insert_text(line)
                err = process.stderr
                if err:
                    stderr_line = err.readline().strip()
                    if stderr_line:
                        line = stderr_line.decode("gbk")
                        self.insert_text(line)
        except Exception as e:
            self.insert_text(e)

    def insert_text(self, text):
        self.text.insert(tkinter.END, text)
        self.text.see(END)

    def clear_text(self):
        self.text.delete('0', END)

    def on_btn_cancel_click(self):
        self.top_level.destroy()

    def on_btn_cancel_hover(self, event):
        self.btn_cancel.config(bg='LightCoral')

    def on_btn_cancel_no_hover(self, event):
        self.btn_cancel.config(background='IndianRed')